//
//  HomeViewController.m
//  intelligent
//
//  Created by 甘世清 on 2024/2/5.
//

#import "HomeViewController.h"
#import "MessageCell.h"
#import "MessageView.h"
#import "HomeHeaderView.h"
#import "MessageLeftTableViewCell.h"
#import "MessageRifhtTableViewCell.h"
#import "MessageModel.h"
#import <SJVideoPlayer/SJVideoPlayer.h>
#import <QKeyboardEmotionView/QKeyboardEmotionView-umbrella.h>
#import <AVFoundation/AVFoundation.h>
#import "VipView.h"
#import "UpDownButton.h"
#import "CleanView.h"
#import "MeVipViewController.h"
#import "ScoreView.h"
#import "FankuiViewController.h"
@interface HomeViewController ()<QInputBarViewDelegate,QInputBarViewDataSource,InputBoardDataSource,InputBoardDelegate,UITableViewDelegate,UITableViewDataSource,HomeHeaderViewDelegate,AVSpeechSynthesizerDelegate>
//@property (nonatomic,strong) MessageView * messageView;
@property (nonatomic , strong)QInputBarView * putView;
@property (nonatomic,strong) HomeHeaderView * headerView;
@property (nonatomic , strong)QKeyboardManager * keyBoardManager;
@property (nonatomic , strong)SJVideoPlayer * player;
@property (nonatomic , strong) AVSpeechSynthesizer * synthesizer;
@property (nonatomic , strong) NSIndexPath * seletedIndexpath;
@property (nonatomic , strong) JQFMDB * db;
@property (nonatomic , strong) UILabel * titleLabel;
@property (nonatomic, assign) BOOL  isSend;
 
@end

@implementation HomeViewController
- (void)dealloc{
    DTLog(@"语音是否释放");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self SQ_Header];
    if (![UserModel share].isVip) {
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat: @"%@%@%@",SQNSLocalString(@"您还有"),[UserModel share].freeCount,SQNSLocalString(@"次免费咨询次数")] attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:14],NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#ffffff"]}];
        [string addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#FF3B30"]} range:NSMakeRange(3, [UserModel share].freeCount.length)];
        self.titleLabel.attributedText = string;
        [self zx_addCustomTitleView:self.titleLabel];
    }else{
        [self.titleLabel removeFromSuperview];
        [self zx_addCustomTitleView:[UIView new]];
    }
    NSInteger rows = [self.tableView numberOfRowsInSection:0];
    if (rows > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 避免手势返回的时候输入框往下掉
    WS(weakSelf);
    [weakSelf.synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryWord];
}

- (void)SQ_Header{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [HttpTool post:@"user/info" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        UserModel * mo = [UserModel share];
        UserModel* model = [UserModel mj_objectWithKeyValues:httpModel.data];
        model.token = mo.token;
        [UserModel updateLocalUserModel:model];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _db = [JQFMDB shareDatabase];
    NSArray * array = [_db jq_lookupTable:HomeHistoryTable dicOrModel:[MessageModel class] whereFormat:nil];
    if (array.count > 0) {
        self.jsonArray = [NSMutableArray arrayWithArray:array];
    }else{
        self.jsonArray = [NSMutableArray array];
    }
    [self zx_setLeftBtnWithImg:SQGetImage(@"vip") clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        MeVipViewController  * vc = [[MeVipViewController alloc]init];
        [[Manager SQ_getCurrentViewController].navigationController pushViewController:vc animated:YES];
    }];
    UpDownButton * rightBtn = [UpDownButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
    [rightBtn setImage:SQGetImage(@"清理") forState:UIControlStateNormal];
    [rightBtn setTitle:SQNSLocalString(@"清理") forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    rightBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [rightBtn addTarget:self action:@selector(clickCleanHistoryBtn) forControlEvents:UIControlEventTouchUpInside];
    self.zx_navRightBtn.zx_customView = rightBtn;
}

-(void)clickCleanHistoryBtn{
    CleanView  * view = [[CleanView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
    LSTPopView * pop = [LSTPopView initWithCustomView:view
                                           parentView:nil
                                             popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
    pop.hemStyle = LSTHemStyleCenter;
    [pop pop];
    LSTPopViewWK(pop)
    [pop setBgClickBlock:^{
        [wk_pop dismiss];
    }];
    WS(weakSelf);
    [view setClickCancelBlock:^{
        [wk_pop dismiss];
    }];
    [view setClickCleanBlock:^{
        [wk_pop dismiss];
        [weakSelf.db jq_deleteAllDataFromTable:HomeHistoryTable];
        [weakSelf.jsonArray removeAllObjects];
        [weakSelf.tableView reloadData];
    }];
}

-(void)SQ_UIViewForSelfView{
    UIImageView * backImageView = [UIImageView new];
    backImageView.image = SQGetImage(@"背景");
    backImageView.frame = CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_WIDETH / 375 * 184);
    [self.view addSubview:backImageView];
//    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(scrollViewWillBeginDragging:)];
//    [self.tableView addGestureRecognizer:tap];
    self.tableView.delegate = self;
    self.tableView.dataSource = self; 
    self.tableView.bounces = NO;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.zx_navBar.mas_bottom);
        make.bottom.equalTo(self.view.mas_bottom).offset(-60);
    }];
    _headerView = [[HomeHeaderView alloc]init];
    _headerView.frame = CGRectMake(0, 0, SCREEN_WIDETH, 215 + 56 * 4 + 30);
    _headerView.delegate = self;
    _headerView.backgroundColor = [UIColor clearColor];
    self.tableView.tableHeaderView = _headerView;
    
    [self.keyBoardManager addBottomInputBarView:self.putView belowViewController:NO];
    [self.keyBoardManager bindTextView:self.putView.inputTextView];
 
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.zx_navBar.mas_bottom);
        make.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.putView.mas_top);
    }];
    self.tableView.backgroundColor = [UIColor clearColor];
    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(scrollViewWillBeginDragging:)];
    WS(weakSelf);
    NSOperationQueue*  mainQueue = [NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification object:nil queue:mainQueue usingBlock:^(NSNotification * _Nonnull note) {
        [weakSelf.tableView addGestureRecognizer:tap];
    }];
    [nc addObserverForName:UIKeyboardWillHideNotification object:nil queue:mainQueue usingBlock:^(NSNotification * _Nonnull note) {
        [weakSelf.tableView removeGestureRecognizer:tap];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.jsonArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(weakSelf);
    MessageModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    NSString * Identifier = [NSString stringWithFormat:@"MessageLeftTableViewCell%ld",(long)indexPath.item];
    if (model.sendType) {
        MessageLeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
        if (!cell) {
            cell = [[MessageLeftTableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:Identifier];
        }
        model.portrait = @"智能 头像";
        cell.model = model;
        [cell.loveBtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
            [weakSelf SQ_LoveBtnClick:model indexPath:indexPath];
        }];
        [cell setTypewriteEffectBlock:^{
            [weakSelf SQ_YuyinBtnClickindexPath:indexPath];
        }];
       
        [cell.fuzhiBtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
            [weakSelf UIPasteboard:model];
        }];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        Identifier = [NSString stringWithFormat:@"MessageRifhtTableViewCell%ld",(long)indexPath.item];
        MessageRifhtTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
        if (!cell) {
            cell = [[MessageRifhtTableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:Identifier];
        }
        model.portrait = [UserModel share].portraitname;
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.keyBoardManager hideAllBoardView];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    if (model.sendType) {
        return model.cellSize.height + 62+22+18;
    }
   return  [MessageRifhtTableViewCell FSCellHeightForTableView:tableView indexPath:indexPath cellContentViewWidth:0 bottomOffset:10];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    //用户手动拖动tableview，隐藏所有面板和键盘
    [self.keyBoardManager hideAllBoardView];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.keyBoardManager hideAllBoardView];
}

-(void)clickQuestion:(NSString *)question{
    [self.keyBoardManager hideAllBoardView];
    self.putView.inputTextView.text = question;
}

-(BOOL)SQ_alreadyAtBottom:(UITableView*)view{
    if (((NSInteger)view.contentOffset.y) == ((NSInteger)view.contentSize.height + view.adjustedContentInset.bottom - CGRectGetHeight(view.bounds))) {
        return YES;
    }
    return NO;
}

//点击了系统键盘的发送按钮
- (void)inputBarView:(QInputBarView *)inputBarView onKeyboardSendClick:(NSString *)inputNormalText {
   //发送消息
    if (![inputNormalText isNotEmpty]) {
        return;
    }
    if (self.isSend) {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"助理当前正在全力思考中!")];
        return;
    }
    if (![UserModel share].isVip) {
        UserModel * mo = [UserModel share];
        if (mo.freeCount.integerValue == 0) {
            [self pushVIPAlert];
            return;
        }
        NSInteger count = mo.freeCount.integerValue - 1;
        if (count <=0) {
            count = 0;
        }
        mo.freeCount = [NSString stringWithFormat:@"%ld",count];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat: @"%@%ld%@",SQNSLocalString(@"您还有"),count,SQNSLocalString(@"次免费咨询次数")] attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:14],NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#ffffff"]}];
        [string addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#FF3B30"]} range:NSMakeRange(3, [UserModel share].freeCount.length)];
        self.titleLabel.attributedText = string;
        [UserModel updateLocalUserModel:mo];
    }
    self.isSend = YES;
    UserModel * usermodel = [UserModel share];
    MessageModel * model  = [MessageModel new]; //创建我发的消息
    model.portrait =usermodel.portraitname;
    model.name = usermodel.name;
    model.content = inputNormalText;
    [self.jsonArray addObject:model];
    [self insertAndScrollToBottom:model needClearInputText:YES];
    MessageModel * model2  = [MessageModel new];//创建假的回复消息
    model2.name = @"";
    model2.sendType = YES; //发送对象
    model2.type = 1; //类型为1
    [self.jsonArray addObject:model2];
    [self insertAndScrollToBottom:model2 needClearInputText:YES];
    NSDictionary * dic = @{
       @"content":inputNormalText
    };
    WS(weakSelf);
    [HttpTool post:SYDA paramDic:[NSMutableDictionary dictionaryWithDictionary:dic] successBlock:^(BaseModel * _Nonnull httpModel) {
       
        MessageModel * newModel = [MessageModel mj_objectWithKeyValues:httpModel.data];
        [weakSelf.db jq_insertTable:HomeHistoryTable dicOrModel:model];
        [weakSelf.db jq_insertTable:HomeHistoryTable dicOrModel:newModel];
        newModel.typewriterType = 1;
        weakSelf.isSend = NO;
        [weakSelf.jsonArray removeObject:model2];//成功了删除假的消息
        [weakSelf.jsonArray addObject:newModel];
        [weakSelf insertAndScrollToBottom:newModel needClearInputText:YES];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        weakSelf.isSend = NO;
        [weakSelf.jsonArray removeObject:model]; //失败了删除添加的内容
        [weakSelf.jsonArray removeObject:model2];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.jsonArray.count <0) {
                [weakSelf insertAndScrollToBottom:[weakSelf.jsonArray lastObject] needClearInputText:YES];
            } else {
                [weakSelf scrollToBottomAnimated:YES];
            }
            inputBarView.inputTextView.text = inputNormalText;
            [YJProgressHUD showMsgWithoutView:httpModel.message];
        });
    }];

    self.putView.inputTextView.text = nil;
    //隐藏键盘
    [self.keyBoardManager hideAllBoardView];
}

-(void)pushScoreView{
    ScoreView  * view = [[ScoreView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
    LSTPopView * pop = [LSTPopView initWithCustomView:view
                                           parentView:nil
                                             popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
    pop.hemStyle = LSTHemStyleCenter;
    [pop pop];
    LSTPopViewWK(pop)
    [pop setBgClickBlock:^{
        [wk_pop dismiss];
    }];
    [view setClickCancelBtnBlock:^{
        [wk_pop dismiss];
    }];
    [view setClickConfireBtnBlock:^{
        [wk_pop dismiss];
        [SKStoreReviewController requestReview];
    }];
    [view setClickFeedbackBtnBlock:^{
        [wk_pop dismiss];
        FankuiViewController *vc = [[FankuiViewController alloc]init];
        [self SQ_pushViewControllerFull:vc];
    }];
}

-(void)pushVIPAlert{
    [self.view endEditing:YES];
    if (![UserModel share].isVip) {
        VipView * view = [[VipView alloc]init];
        view.frame = CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT);
        LSTPopView * pop = [LSTPopView initWithCustomView:view
                                               parentView:nil
                                                 popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
        pop.hemStyle = LSTHemStyleCenter;
        [pop pop];
        LSTPopViewWK(pop)
        [pop setBgClickBlock:^{
            [wk_pop dismiss];
        }];
      
        [view setOpenVIPBlock:^{
            [wk_pop dismiss];
            MeVipViewController  * vc = [[MeVipViewController alloc]init];
            [[Manager SQ_getCurrentViewController].navigationController pushViewController:vc animated:YES];
        }];
        [view setCloseViewBlock:^{
            [wk_pop dismiss];
        }];
    }
}

-(void)sendQuestion:(NSString *)question{
    [self inputBarView:self.putView onKeyboardSendClick:question];
}

-(void)sendMessageWithText{
    //发送给服务器
    [self inputBarView:self.putView onKeyboardSendClick:[self.putView textViewInputNormalText]];
}

//添加到array中 + reload和滚到底部。 needClearInputText: 是否需要清空文本框输入的内容
- (void)insertAndScrollToBottom:(MessageModel *)contentModel needClearInputText:(BOOL)needClearInputText {
    if (contentModel ==nil) {
        return;
    }
    //添加到array中
    NSTimeInterval animationDuration = needClearInputText ? [self.putView clearInputTextBySend] : 0;
    //reloadData并滚到底部
    [self reloadDataAndScrollToBottomAnimated:YES animationDelay:animationDuration];
}
//reloadData并滚到底部
- (void)reloadDataAndScrollToBottomAnimated:(BOOL)animated animationDelay:(NSTimeInterval)animationDelay {
     BOOL resultAnimated = animated;
    if (animationDelay == 0){
        //如果textView的文本只有一行，那么清空输入框的时候，不会走onWholeInputViewHeightDidChange回调，也不会重新设置tableView的contentInset。所以就无需延时reloadData
        [self.tableView reloadData];
        [self scrollToBottomAnimated:resultAnimated];
    } else {
        //textView的文本大于一行，那么清空输入框的时候，会重设tableView的contentInset（并且我还是在0.2秒的动画里重设的），如果这时候reloadData，在低性能设备上会出现tableView来回上下移动的问题
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(animationDelay * NSEC_PER_SEC)), dispatch_get_main_queue(),  ^{
            [self.tableView reloadData];
            [self scrollToBottomAnimated:resultAnimated];
        });
    }
}
//滚到底部
-(void)scrollToBottomAnimated:(BOOL)animated {
    if (self.player.timeControlStatus == SJPlaybackTimeControlStatusPlaying) {
        MessageLeftTableViewCell * cell = [self.tableView cellForRowAtIndexPath:self.seletedIndexpath];
        [cell.lottieView play];
    }
    NSInteger rows = [self.tableView numberOfRowsInSection:0];
    if (rows > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    }
}

#pragma mark - InputBoardDelegate
//整个“输入View”的高度发生变化（整个View包含bar和表情栏或者键盘，但是不包含底部安全区高度）
- (void)keyboardManager:(QKeyboardManager *)keyboardManager onWholeInputViewHeightDidChange:(CGFloat)wholeInputViewHeight reason:(WholeInputViewHeightDidChangeReason)reason {
    WS(weakSelf);
    BOOL alreadyAtBottom = [self SQ_alreadyAtBottom:weakSelf.tableView];
    UIEdgeInsets insets = UIEdgeInsetsZero;
    insets.top = 0;
    insets.bottom = wholeInputViewHeight - 60;
    //对应聊天界面，随着底部输入框的frame.y的变化，为了保持tableview一直都在输入条的上方，修改tableview的contentInset
    self.tableView.contentInset = insets;
    self.tableView.scrollIndicatorInsets = insets;
    if (reason == WholeInputViewHeightDidChangeReasonWillAddToSuperView) {
        //聊天界面，tableView要滚到底部
        dispatch_async(dispatch_get_main_queue(), ^{
        [self scrollToBottomAnimated:NO];
     });
        return;
    }
    if (reason == WholeInputViewHeightDidChangeReasonTextDidSend) {
        //是点击“发送”按钮清空输入框里的多行文字导致的输入栏高度变化
        return;
    }
    if (alreadyAtBottom) {
        //用自己的animations，问题就是会闪屏，尤其是tableview滚在上方时候 闪的越狠；好处是tableview在切换时候很跟手
        [UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            [self scrollToBottomAnimated:YES];
        } completion:nil];
    } else {
        [self scrollToBottomAnimated:YES];
    }
}

#pragma mark - QInputBarViewDataSource
//@return 输入条上的UITextView，返回你自定义的UITextView
- (UITextView *)textViewForInputBarView:(QInputBarView *)inputBarView {
    FSTextView *tv = [[FSTextView alloc] init];
    tv.layer.cornerRadius = 4;
    tv.placeholder = @"这里输入你的问题...";
    return tv;
}
#pragma mark - QInputBarViewDelegate
// 输入框的高度发生了改变（因为输入框里的文字行数变化了），注意这里仅仅是TextView输入框的高度发生了变化的回调；becauseSendText：YES表示是因为调用了clearInputTextBySend去发送文本
- (void)inputBarView:(QInputBarView *)inputBarView inputTextView:(UITextView *)inputTextView heightDidChange:(CGFloat)changeValue becauseSendText:(BOOL)becauseSendText {
    //这里要告知Manager类
    [self.keyBoardManager inputTextViewHeightDidChange:becauseSendText];
}

-(void)UIPasteboard:(MessageModel*)model
{
    UIPasteboard *pab = [UIPasteboard generalPasteboard];
      pab.string = model.content;
      if (pab == nil) {
          [YJProgressHUD showMessage:SQNSLocalString(@"复制失败")inView:self.tableView];
      } else {
          [YJProgressHUD showMessage:SQNSLocalString(@"复制成功")inView:self.tableView];
      }
}
-(void)SQ_LoveBtnClick:(MessageModel*)model indexPath:(NSIndexPath*)indexPath{
    if (!model.userid) {
        return;
    }
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:model.userid forKey:@"id"];
    if (model.isCollect) {
        [dic setObject:@"0" forKey:@"type"];
    } else {
        [dic setObject:@"1" forKey:@"type"];
    }
    [HttpTool post:@"chat/collect" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        model.isCollect = !model.isCollect;
        [[JQFMDB shareDatabase] jq_updateTable:HomeHistoryTable dicOrModel:model whereFormat:[NSString stringWithFormat:@"where userid = '%@'",model.userid]];
        MessageLeftTableViewCell * cell1 = [self.tableView cellForRowAtIndexPath:indexPath];
        if (model.isCollect) {
             cell1.loveBtn.image = SQGetImage(@"收藏-亮");
            [YJProgressHUD showMessage:SQNSLocalString(@"收藏成功，个人中心收藏中查看") inView:self.tableView];
        } else {
            cell1.loveBtn.image = SQGetImage(@"收藏-灰");
        }
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
}

-(void)SQ_YuyinBtnClickindexPath:(NSIndexPath*)indexPath {
    
    if (self.seletedIndexpath) {
        MessageLeftTableViewCell * cell1 = [self.tableView cellForRowAtIndexPath:self.seletedIndexpath];
        [cell1 SQ_UISetUp];
        [self.player stop];
        [self.synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryWord];
        if (self.seletedIndexpath.item == indexPath.item) {
            self.seletedIndexpath = nil;
            return;
        }
    }
    MessageLeftTableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
    dispatch_async(dispatch_get_main_queue(), ^{
          [cell.hud stopAnimating];
        cell.yuyinBtn.backgroundColor = UIColor.clearColor;
     });
    [cell.lottieView play];
    WS(weakSelf);
    if ([cell.model.url isNotEmpty]) {
        self.player.assetURL = [NSURL URLWithString:[cell.model.url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
        [self.player.playbackObserver setPlaybackDidFinishExeBlock:^(__kindof SJBaseVideoPlayer * _Nonnull player) {
            MessageLeftTableViewCell * cell = [weakSelf.tableView cellForRowAtIndexPath:weakSelf.seletedIndexpath];
            [cell.lottieView stop];
        }];
    } else {
         //本地播放
        AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:cell.model.content];
        utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
        [self.synthesizer speakUtterance:utterance];
    }
    self.seletedIndexpath = indexPath;
}
//系统播放终止
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance{
    if (self.seletedIndexpath) {
        MessageLeftTableViewCell * cell1 = [self.tableView cellForRowAtIndexPath:self.seletedIndexpath];
        [cell1.lottieView stop];
    }
}


- (QKeyboardManager *)keyBoardManager{
    if (!_keyBoardManager) {
        _keyBoardManager = [[QKeyboardManager alloc]initWithViewController:self];
        _keyBoardManager.dataSource = self;
        _keyBoardManager.delegate = self;
    }
    return _keyBoardManager;
}
 
- (SJVideoPlayer *)player{
    if (!_player) {
        _player = [SJVideoPlayer player];
    }
    return _player;
}
- (AVSpeechSynthesizer *)synthesizer{
    if (!_synthesizer) {
        _synthesizer = [[AVSpeechSynthesizer alloc] init];
        _synthesizer.delegate = self;
    }
    return _synthesizer;
}

-(UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.backgroundColor = [UIColor colorWithHexString:@"#333333"];
        _titleLabel.layer.cornerRadius = 16;
        _titleLabel.layer.masksToBounds = YES;
        _titleLabel.frame = CGRectMake(0, 0, 230, 32);
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}

- (QInputBarView *)putView{
    if (!_putView) {
        _putView = [[QInputBarView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-FootHeight, SCREEN_WIDETH, 60)];
        _putView.delegate = self;
        _putView.dataSource = self;
        QInputBarViewConfiguration *config = [QInputBarViewConfiguration defaultInputBarViewConfiguration];
        config.inputBarBackgroundColor = SQColor(@"#FFFFFF");
        config.inputBarBoardColor = UIColor.whiteColor;
        config.textViewBackgroundColor = SQColor(@"#EEEEEE");
        config.textColor = SQColor(@"#EEEEEE");
        config.voiceButtonHidden = YES;
        config.emotionButtonHidden = YES;
        config.extendButtonHidden = YES;
        UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 42, 42)];
        [btn addTarget:self action:@selector(sendMessageWithText) forControlEvents:UIControlEventTouchUpInside];
        [btn setImage:SQGetImage(@"发送-亮") forState:normal];
        config.rightSendButton = btn;
        [_putView setupWithConfiguration:config];
       
        _putView.inputTextView.textColor = SQColor(@"#333333");
//        _putView.inputTextView.textContainerInset = UIEdgeInsetsMake(30, 10, 10, 10);
    }
    return _putView;
}
@end
